#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <cmath>
#include <QByteArray>
#include <QDebug>
#include <QRandomGenerator>
#include <QCoreApplication>
#include <QDir>

// 将角度转换为弧度，并限制在 0 ~ 2*PI
constexpr int degreesToRadians(double degrees) {
    double rad = degrees * M_PI / 180.0;
    // 保证弧度在 0 ~ 2*PI
    rad = std::fmod(rad, 2 * M_PI);
    if (rad < 0) rad += 2 * M_PI;
    return rad * 100 + 1;
}

// 将弧度转换为角度，并限制在 0 ~ 360
constexpr double radiansToDegrees(double radians) {
    double deg = radians * 180.0 / M_PI;
    // 保证角度在 0 ~ 360
    deg = std::fmod(deg, 360.0);
    if (deg < 0) deg += 360.0;
    return deg;
}

// 添加噪声函数：对数值的最后两位添加随机扰动
// 添加噪声函数：对数值添加指定范围的随机扰动
int MainWindow::addNoise(int originalValue, int noiseRange) {
    if (!m_noiseEnabled) {
        return originalValue;
    }
    
    // 生成-noiseRange到+noiseRange之间的随机扰动
    int noise = QRandomGenerator::global()->bounded(-noiseRange, noiseRange + 1);
    int noisyValue = originalValue + noise;
    
    // 调试输出：显示噪声效果
    qDebug() << "噪声应用: 原值 =" << originalValue << ", 噪声范围 = ±" << noiseRange << ", 噪声 =" << noise << ", 结果 =" << noisyValue;
    
    return noisyValue;
}


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_noiseEnabled(false)  // 初始化噪声状态为关闭
{
    ui->setupUi(this);

    // 创建UDP发送器
    QHostAddress ip(ui->lineEdit_ip->text());
    quint16 port = ui->lineEdit_port->text().toUShort();
    m_sender = new UdpSender(ip, port, this);
    qDebug() << "UDP Sender initialized with IP:" << ip.toString() << "Port:" << port;

    // 加载JSON配置文件
    qDebug() << "Loading JSON configuration file...";
    loadDataFromJson();

    // 初始化定时器
    m_timerCar1 = new QTimer(this);
    m_timerCar2 = new QTimer(this);
    m_timerDrone = new QTimer(this);
    
    // 连接定时器信号到发送槽函数
    connect(m_timerCar1, &QTimer::timeout, this, &MainWindow::sendCar1Data);
    connect(m_timerCar2, &QTimer::timeout, this, &MainWindow::sendCar2Data);
    connect(m_timerDrone, &QTimer::timeout, this, &MainWindow::sendDroneData);
    
    qDebug() << "MainWindow initialization completed";
}

void MainWindow::loadDataFromJson()
{
    // 使用与exe同目录的data.json文件
    QString jsonFilePath = QCoreApplication::applicationDirPath() + "/data.json";
    
    QFile file(jsonFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "[ERROR] 无法打开JSON文件:" << jsonFilePath;
        return;
    }
    
    qDebug() << "Successfully opened data.json file:" << jsonFilePath;
    
    QByteArray jsonData = file.readAll();
    file.close();
    
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);
    
    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "JSON parse error:" << parseError.errorString();
        m_useJsonData = false;
        return;
    }
    
    QJsonObject config = doc.object();
    
    // 解析car1数据 - 只读取JSON中存在的字段
    if (config.contains("car1") && config["car1"].isObject()) {
        QJsonObject car1 = config["car1"].toObject();
        
        // 只有当字段存在时才读取和标记
        if (car1.contains("longitude")) {
            m_jsonCar1Data.longitude = car1["longitude"].toInt();
            m_jsonCar1Data.hasLongitude = true;
        }
        if (car1.contains("latitude")) {
            m_jsonCar1Data.latitude = car1["latitude"].toInt();
            m_jsonCar1Data.hasLatitude = true;
        }
        if (car1.contains("heading")) {
            m_jsonCar1Data.heading = car1["heading"].toInt();
            m_jsonCar1Data.hasHeading = true;
        }
        if (car1.contains("label1")) {
            m_jsonCar1Data.label1 = car1["label1"].toInt();
            m_jsonCar1Data.hasLabel1 = true;
        }
        if (car1.contains("deviation1")) {
            m_jsonCar1Data.deviation1 = car1["deviation1"].toInt();
            m_jsonCar1Data.hasDeviation1 = true;
        }
        if (car1.contains("label2")) {
            m_jsonCar1Data.label2 = car1["label2"].toInt();
            m_jsonCar1Data.hasLabel2 = true;
        }
        if (car1.contains("deviation2")) {
            m_jsonCar1Data.deviation2 = car1["deviation2"].toInt();
            m_jsonCar1Data.hasDeviation2 = true;
        }
        if (car1.contains("label3")) {
            m_jsonCar1Data.label3 = car1["label3"].toInt();
            m_jsonCar1Data.hasLabel3 = true;
        }
        if (car1.contains("deviation3")) {
            m_jsonCar1Data.deviation3 = car1["deviation3"].toInt();
            m_jsonCar1Data.hasDeviation3 = true;
        }
        
        m_jsonCar1Data.isValid = true;
        qDebug() << "Loaded car1 data from JSON";
    }
    
    // 解析car2数据 - 只读取JSON中存在的字段
    if (config.contains("car2") && config["car2"].isObject()) {
        QJsonObject car2 = config["car2"].toObject();
        
        // 只有当字段存在时才读取和标记
        if (car2.contains("longitude")) {
            m_jsonCar2Data.longitude = car2["longitude"].toInt();
            m_jsonCar2Data.hasLongitude = true;
        }
        if (car2.contains("latitude")) {
            m_jsonCar2Data.latitude = car2["latitude"].toInt();
            m_jsonCar2Data.hasLatitude = true;
        }
        if (car2.contains("heading")) {
            m_jsonCar2Data.heading = car2["heading"].toInt();
            m_jsonCar2Data.hasHeading = true;
        }
        if (car2.contains("label1")) {
            m_jsonCar2Data.label1 = car2["label1"].toInt();
            m_jsonCar2Data.hasLabel1 = true;
        }
        if (car2.contains("deviation1")) {
            m_jsonCar2Data.deviation1 = car2["deviation1"].toInt();
            m_jsonCar2Data.hasDeviation1 = true;
        }
        if (car2.contains("label2")) {
            m_jsonCar2Data.label2 = car2["label2"].toInt();
            m_jsonCar2Data.hasLabel2 = true;
        }
        if (car2.contains("deviation2")) {
            m_jsonCar2Data.deviation2 = car2["deviation2"].toInt();
            m_jsonCar2Data.hasDeviation2 = true;
        }
        if (car2.contains("label3")) {
            m_jsonCar2Data.label3 = car2["label3"].toInt();
            m_jsonCar2Data.hasLabel3 = true;
        }
        if (car2.contains("deviation3")) {
            m_jsonCar2Data.deviation3 = car2["deviation3"].toInt();
            m_jsonCar2Data.hasDeviation3 = true;
        }
        
        m_jsonCar2Data.isValid = true;
        qDebug() << "Loaded car2 data from JSON";
    }
    
    // 解析drone数据 - 只读取JSON中存在的字段
    if (config.contains("drone") && config["drone"].isObject()) {
        QJsonObject drone = config["drone"].toObject();
        
        // 只有当字段存在时才读取和标记
        if (drone.contains("longitude")) {
            m_jsonDroneData.longitude = drone["longitude"].toInt();
            m_jsonDroneData.hasLongitude = true;
        }
        if (drone.contains("latitude")) {
            m_jsonDroneData.latitude = drone["latitude"].toInt();
            m_jsonDroneData.hasLatitude = true;
        }
        if (drone.contains("altitude")) {
            m_jsonDroneData.altitude = drone["altitude"].toInt();
            m_jsonDroneData.hasAltitude = true;
        }
        if (drone.contains("heading")) {
            m_jsonDroneData.heading = drone["heading"].toInt();
            m_jsonDroneData.hasHeading = true;
        }
        if (drone.contains("roll")) {
            m_jsonDroneData.roll = drone["roll"].toInt();
            m_jsonDroneData.hasRoll = true;
        }
        if (drone.contains("pitch")) {
            m_jsonDroneData.pitch = drone["pitch"].toInt();
            m_jsonDroneData.hasPitch = true;
        }
        if (drone.contains("label1")) {
            m_jsonDroneData.label1 = drone["label1"].toInt();
            m_jsonDroneData.hasLabel1 = true;
        }
        if (drone.contains("target1X")) {
            m_jsonDroneData.target1X = drone["target1X"].toInt();
            m_jsonDroneData.hasTarget1X = true;
        }
        if (drone.contains("target1Y")) {
            m_jsonDroneData.target1Y = drone["target1Y"].toInt();
            m_jsonDroneData.hasTarget1Y = true;
        }
        if (drone.contains("label2")) {
            m_jsonDroneData.label2 = drone["label2"].toInt();
            m_jsonDroneData.hasLabel2 = true;
        }
        if (drone.contains("target2X")) {
            m_jsonDroneData.target2X = drone["target2X"].toInt();
            m_jsonDroneData.hasTarget2X = true;
        }
        if (drone.contains("target2Y")) {
            m_jsonDroneData.target2Y = drone["target2Y"].toInt();
            m_jsonDroneData.hasTarget2Y = true;
        }
        if (drone.contains("label3")) {
            m_jsonDroneData.label3 = drone["label3"].toInt();
            m_jsonDroneData.hasLabel3 = true;
        }
        if (drone.contains("target3X")) {
            m_jsonDroneData.target3X = drone["target3X"].toInt();
            m_jsonDroneData.hasTarget3X = true;
        }
        if (drone.contains("target3Y")) {
            m_jsonDroneData.target3Y = drone["target3Y"].toInt();
            m_jsonDroneData.hasTarget3Y = true;
        }
        
        m_jsonDroneData.isValid = true;
        qDebug() << "Loaded drone data from JSON";
    }
    
    // 如果成功加载了任何数据，启用JSON数据使用
    if (m_jsonCar1Data.isValid || m_jsonCar2Data.isValid || m_jsonDroneData.isValid) {
        m_useJsonData = true;
        qDebug() << "JSON data loaded successfully, using JSON configuration";
        
        // 将JSON数据填充到UI控件中
        updateUIFromJsonData();
    } else {
        m_useJsonData = false;
        qDebug() << "No valid JSON data found, using default configuration";
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 读取 Car 数据
CarData MainWindow::readCarData(int carIndex)
{
    CarData data{};
    QLineEdit *longEdit = nullptr, *latEdit = nullptr, *headingEdit = nullptr;
    QLineEdit *dev1Edit = nullptr, *dev2Edit = nullptr, *dev3Edit = nullptr;
    QLineEdit *label1Edit = nullptr, *label2Edit = nullptr, *label3Edit = nullptr;

    if (carIndex == 1) {
        longEdit = ui->car1_long;
        latEdit = ui->car1_lat;
        headingEdit = ui->car1_heading;
        dev1Edit = ui->car1_dev1;
        dev2Edit = ui->car1_dev2;
        dev3Edit = ui->car1_dev3;
        label1Edit = ui->car1_label1;
        label2Edit = ui->car1_label2;
        label3Edit = ui->car1_label3;
    } else if (carIndex == 2) {
        longEdit = ui->car2_long;
        latEdit = ui->car2_lat;
        headingEdit = ui->car2_heading;
        dev1Edit = ui->car2_dev1;
        dev2Edit = ui->car2_dev2;
        dev3Edit = ui->car2_dev3;
        label1Edit = ui->car2_label1;
        label2Edit = ui->car2_label2;
        label3Edit = ui->car2_label3;
    }

    // 始终从UI输入框读取当前数据，确保用户手动修改能够生效

    // 读取基础数据并添加噪声
    int originalLong = longEdit->text().toInt();
    int originalLat = latEdit->text().toInt();
    int originalHeading = headingEdit->text().toInt();
    
    data.longitude = static_cast<qint32>(addNoise(originalLong, 5));  // longitude是qint32类型，经度噪声范围±5
    data.latitude = static_cast<qint32>(addNoise(originalLat, 5));   // latitude是qint32类型，纬度噪声范围±5
    
    // 航向角归一化到0-360度范围
    double headingWithNoise = addNoise(originalHeading, 100);
    double normalizedHeading = fmod(headingWithNoise, 36000.0);
    if (normalizedHeading < 0) normalizedHeading += 36000.0;
    data.heading = static_cast<quint16>(normalizedHeading);
    
    qDebug() << "Car" << carIndex << "读取UI值 - 经度:" << originalLong << "纬度:" << originalLat << "航向:" << originalHeading;
    qDebug() << "Car" << carIndex << "发送数据 - 经度:" << data.longitude << "纬度:" << data.latitude << "航向:" << data.heading;


    // --- 核心修改：根据label输入框是否有内容，自动计算 count ---
    data.count = 0;
    if (!label1Edit->text().isEmpty()) {
        data.count++;
        data.label1 = static_cast<quint8>(label1Edit->text().toUShort());  // label1是quint8类型
        int originalDev1 = dev1Edit->text().toInt();
        data.deviation1 = static_cast<qint16>(addNoise(originalDev1, 30));  // deviation1是qint16类型，偏离角1噪声范围±300
        qDebug() << "Car" << carIndex << "Label1:" << data.label1 << "原始偏角1:" << originalDev1 << "发送偏角1:" << data.deviation1;
    }
    if (!label2Edit->text().isEmpty()) {
        data.count++;
        data.label2 = static_cast<quint8>(label2Edit->text().toUShort());  // label2是quint8类型
        int originalDev2 = dev2Edit->text().toInt();
        data.deviation2 = static_cast<qint16>(addNoise(originalDev2, 30));  // deviation2是qint16类型，偏离角2噪声范围±300
        qDebug() << "Car" << carIndex << "Label2:" << data.label2 << "原始偏角2:" << originalDev2 << "发送偏角2:" << data.deviation2;
    }
    if (!label3Edit->text().isEmpty()) {
        data.count++;
        data.label3 = static_cast<quint8>(label3Edit->text().toUShort());  // label3是quint8类型
        int originalDev3 = dev3Edit->text().toInt();
        data.deviation3 = static_cast<qint16>(addNoise(originalDev3, 300));  // deviation3是qint16类型，偏离角3噪声范围±300
        qDebug() << "Car" << carIndex << "Label3:" << data.label3 << "原始偏角3:" << originalDev3 << "发送偏角3:" << data.deviation3;
    }

    // 调试输出 count
    qDebug() << "Car" << carIndex << "count:" << data.count;

    return data;
}

// 读取 Drone 数据
DroneData MainWindow::readDroneData()
{
    DroneData data{};
    // 读取基础数据并添加噪声
    int originalLong = ui->drone_long->text().toInt();
    int originalLat = ui->drone_lat->text().toInt();
    int originalAlt = ui->drone_alt->text().toInt();
    int originalHeading = ui->drone_heading->text().toInt();
    
    data.longitude = static_cast<qint32>(addNoise(originalLong, 5));  // longitude是qint32类型，经度噪声范围±5
    data.latitude = static_cast<qint32>(addNoise(originalLat, 5));   // latitude是qint32类型，纬度噪声范围±5
    data.altitude = static_cast<quint16>(addNoise(originalAlt, 5));    // altitude是quint16类型，高度噪声范围±5
    
    qDebug() << "Drone读取UI值 - 经度:" << originalLong << "纬度:" << originalLat << "高度:" << originalAlt << "航向:" << originalHeading;
    
    // 对角度数据添加噪声后再转换为弧度
    int originalRoll = ui->drone_roll->text().toInt();
    int originalPitch = ui->drone_pitch->text().toInt();
    
    double headingWithNoise = addNoise(originalHeading, 100);  // 航向角噪声范围±100
    double rollWithNoise = addNoise(originalRoll, 100);     // 横滚角噪声范围±100
    double pitchWithNoise = addNoise(originalPitch, 100);   // 俯仰角噪声范围±100
    
    // 航向角归一化到0-360度范围
    double normalizedHeading = fmod(headingWithNoise, 36000.0);
    if (normalizedHeading < 0) normalizedHeading += 36000.0;
    data.heading = static_cast<quint16>(normalizedHeading);
    
    // 横滚角归一化到-180到180度范围
    double normalizedRoll = fmod(rollWithNoise + 18000.0, 36000.0) - 18000.0;
    if (normalizedRoll < -18000.0) normalizedRoll += 36000.0;
    data.roll = static_cast<qint16>(normalizedRoll);  // 转换为-180到180存储
    
    // 俯仰角归一化到-180到180度范围
    double normalizedPitch = fmod(pitchWithNoise + 18000.0, 36000.0) - 18000.0;
    if (normalizedPitch < -18000.0) normalizedPitch += 36000.0;
    data.pitch = static_cast<qint16>(normalizedPitch);  // 转换为-180到180存储
    
    qDebug() << "Drone发送数据 - 经度:" << data.longitude << "纬度:" << data.latitude << "高度:" << data.altitude;
    qDebug() << "Drone发送数据 - 航向:" << data.heading << "横滚:" << data.roll << "俯仰:" << data.pitch;



    // --- 核心修改：根据label输入框是否有内容，自动计算 count ---
    data.count = 0;
    if (!ui->drone_label1->text().isEmpty()) {
        data.count++;
        data.label1 = static_cast<quint8>(ui->drone_label1->text().toUShort());  // label1是quint8类型
        // 增强代码健壮性，防止split后访问越界，并添加噪声
        QStringList parts = ui->drone_t1->text().split(',');
        int originalX1 = (parts.size() > 0) ? parts[0].toInt() : 0;
        int originalY1 = (parts.size() > 1) ? parts[1].toInt() : 0;
        data.target1X = static_cast<quint16>(addNoise(originalX1, 30));  // target1X是quint16类型，目标1X坐标噪声范围±300
        data.target1Y = static_cast<quint16>(addNoise(originalY1, 30));  // target1Y是quint16类型，目标1Y坐标噪声范围±300
        qDebug() << "Drone Label1:" << data.label1 << "原始target1(" << originalX1 << "," << originalY1 << ") 发送target1(" << data.target1X << "," << data.target1Y << ")";
    }
    if (!ui->drone_label2->text().isEmpty()) {
        data.count++;
        data.label2 = static_cast<quint8>(ui->drone_label2->text().toUShort());  // label2是quint8类型
        QStringList parts = ui->drone_t2->text().split(',');
        int originalX2 = (parts.size() > 0) ? parts[0].toInt() : 0;
        int originalY2 = (parts.size() > 1) ? parts[1].toInt() : 0;
        data.target2X = static_cast<quint16>(addNoise(originalX2, 30));  // target2X是quint16类型，目标2X坐标噪声范围±300
        data.target2Y = static_cast<quint16>(addNoise(originalY2, 30));  // target2Y是quint16类型，目标2Y坐标噪声范围±300
        qDebug() << "Drone Label2:" << data.label2 << "原始target2(" << originalX2 << "," << originalY2 << ") 发送target2(" << data.target2X << "," << data.target2Y << ")";
    }
    if (!ui->drone_label3->text().isEmpty()) {
        data.count++;
        data.label3 = static_cast<quint8>(ui->drone_label3->text().toUShort());  // label3是quint8类型
        QStringList parts = ui->drone_t3->text().split(',');
        int originalX3 = (parts.size() > 0) ? parts[0].toInt() : 0;
        int originalY3 = (parts.size() > 1) ? parts[1].toInt() : 0;
        data.target3X = static_cast<quint16>(addNoise(originalX3, 30));  // target3X是quint16类型，目标3X坐标噪声范围±300
        data.target3Y = static_cast<quint16>(addNoise(originalY3, 30));  // target3Y是quint16类型，目标3Y坐标噪声范围±300
        qDebug() << "Drone Label3:" << data.label3 << "原始target3(" << originalX3 << "," << originalY3 << ") 发送target3(" << data.target3X << "," << data.target3Y << ")";
    }

    // 调试输出 count
    qDebug() << "Drone count:" << data.count;

    return data;
}

// --- 新增：实际发送数据的槽函数 ---
void MainWindow::sendCar1Data()
{
    CarData data = readCarData(1);
    m_sender->sendCar1(data);
    qDebug() << "定时发送 Car1 数据...";
}

void MainWindow::sendCar2Data()
{
    CarData data = readCarData(2);
    m_sender->sendCar2(data);
    qDebug() << "定时发送 Car2 数据...";
}

void MainWindow::sendDroneData()
{
    DroneData data = readDroneData();
    m_sender->sendDrone(data);
    qDebug() << "定时发送 Drone 数据...";
}


// --- 修改：按钮点击事件现在用于控制定时器的启停 ---
void MainWindow::on_sendCar1_clicked()
{
    if (m_timerCar1->isActive()) {
        m_timerCar1->stop();
        ui->sendCar1->setText("发送Car1"); // 恢复按钮文本
        qDebug() << "停止发送 Car1";
    } else {
        int interval = getCurrentInterval();  // 使用用户设置的频率
        m_timerCar1->start(interval);
        ui->sendCar1->setText("停止发送Car1"); // 更改按钮文本以提示状态
        qDebug() << "开始连续发送 Car1，间隔:" << interval << "毫秒";
    }
}

void MainWindow::on_sendCar2_clicked()
{
    if (m_timerCar2->isActive()) {
        m_timerCar2->stop();
        ui->sendCar2->setText("发送Car2");
        qDebug() << "停止发送 Car2";
    } else {
        int interval = getCurrentInterval();  // 使用用户设置的频率
        m_timerCar2->start(interval);
        ui->sendCar2->setText("停止发送Car2");
        qDebug() << "开始连续发送 Car2，间隔:" << interval << "毫秒";
    }
}

void MainWindow::on_sendDrone_clicked()
{
    if (m_timerDrone->isActive()) {
        m_timerDrone->stop();
        ui->sendDrone->setText("发送Drone");
        qDebug() << "停止发送 Drone";
    } else {
        int interval = getCurrentInterval();  // 使用用户设置的频率
        m_timerDrone->start(interval);
        ui->sendDrone->setText("停止发送Drone");
        qDebug() << "开始连续发送 Drone，间隔:" << interval << "毫秒";
    }
}

// 重设UDP连接的槽函数
void MainWindow::on_btnResetConnection_clicked()
{
    // 获取新的IP和端口
    QHostAddress newIp(ui->lineEdit_ip->text());
    quint16 newPort = ui->lineEdit_port->text().toUShort();
    
    // 删除旧的发送器
    if (m_sender) {
        delete m_sender;
    }
    
    // 创建新的发送器
    m_sender = new UdpSender(newIp, newPort, this);
    
    qDebug() << "UDP连接已重设为:" << newIp.toString() << ":" << newPort;
}

// 切换噪声状态的槽函数
void MainWindow::on_btnToggleNoise_clicked()
{
    m_noiseEnabled = !m_noiseEnabled;
    
    if (m_noiseEnabled) {
        ui->btnToggleNoise->setText("关闭噪声");
        qDebug() << "噪声已启用";
    } else {
        ui->btnToggleNoise->setText("启动噪声");
        qDebug() << "噪声已关闭";
    }
}

// 设置发送频率的槽函数
void MainWindow::on_btnSetFrequency_clicked()
{
    // 获取用户输入的频率值
    bool ok;
    double frequency = ui->lineEdit_frequency->text().toDouble(&ok);
    
    // 检查输入是否有效
    if (!ok || frequency <= 0) {
        qDebug() << "无效的频率值，请输入大于0的数字";
        return;
    }
    
    // 计算定时器间隔（毫秒）= 1000 / 频率
    int interval = static_cast<int>(1000.0 / frequency);
    
    // 确保间隔至少为1毫秒
    if (interval < 1) interval = 1;
    
    // 更新所有定时器的间隔
    if (m_timerCar1) {
        bool wasActive1 = m_timerCar1->isActive();
        if (wasActive1) {
            m_timerCar1->stop();
            m_timerCar1->start(interval);
        }
    }
    
    if (m_timerCar2) {
        bool wasActive2 = m_timerCar2->isActive();
        if (wasActive2) {
            m_timerCar2->stop();
            m_timerCar2->start(interval);
        }
    }
    
    if (m_timerDrone) {
        bool wasActive3 = m_timerDrone->isActive();
        if (wasActive3) {
            m_timerDrone->stop();
            m_timerDrone->start(interval);
        }
    }
    
    qDebug() << "发送频率已设置为" << frequency << "Hz，间隔为" << interval << "毫秒";
}

// 将JSON数据更新到UI控件
void MainWindow::updateUIFromJsonData()
{
    // 更新Car1数据到UI - 只更新JSON中存在的字段
    if (m_jsonCar1Data.isValid) {
        if (m_jsonCar1Data.hasLongitude) {
            ui->car1_long->setText(QString::number(m_jsonCar1Data.longitude));
        }
        if (m_jsonCar1Data.hasLatitude) {
            ui->car1_lat->setText(QString::number(m_jsonCar1Data.latitude));
        }
        if (m_jsonCar1Data.hasHeading) {
            ui->car1_heading->setText(QString::number(m_jsonCar1Data.heading));
        }
        if (m_jsonCar1Data.hasLabel1) {
            ui->car1_label1->setText(QString::number(m_jsonCar1Data.label1));
        }
        if (m_jsonCar1Data.hasDeviation1) {
            ui->car1_dev1->setText(QString::number(m_jsonCar1Data.deviation1));
        }
        if (m_jsonCar1Data.hasLabel2) {
            ui->car1_label2->setText(QString::number(m_jsonCar1Data.label2));
        }
        if (m_jsonCar1Data.hasDeviation2) {
            ui->car1_dev2->setText(QString::number(m_jsonCar1Data.deviation2));
        }
        if (m_jsonCar1Data.hasLabel3) {
            ui->car1_label3->setText(QString::number(m_jsonCar1Data.label3));
        }
        if (m_jsonCar1Data.hasDeviation3) {
            ui->car1_dev3->setText(QString::number(m_jsonCar1Data.deviation3));
        }
        qDebug() << "Car1 data updated to UI (only existing fields)";
    }
    
    // 更新Car2数据到UI - 只更新JSON中存在的字段
    if (m_jsonCar2Data.isValid) {
        if (m_jsonCar2Data.hasLongitude) {
            ui->car2_long->setText(QString::number(m_jsonCar2Data.longitude));
        }
        if (m_jsonCar2Data.hasLatitude) {
            ui->car2_lat->setText(QString::number(m_jsonCar2Data.latitude));
        }
        if (m_jsonCar2Data.hasHeading) {
            ui->car2_heading->setText(QString::number(m_jsonCar2Data.heading));
        }
        if (m_jsonCar2Data.hasLabel1) {
            ui->car2_label1->setText(QString::number(m_jsonCar2Data.label1));
        }
        if (m_jsonCar2Data.hasDeviation1) {
            ui->car2_dev1->setText(QString::number(m_jsonCar2Data.deviation1));
        }
        if (m_jsonCar2Data.hasLabel2) {
            ui->car2_label2->setText(QString::number(m_jsonCar2Data.label2));
        }
        if (m_jsonCar2Data.hasDeviation2) {
            ui->car2_dev2->setText(QString::number(m_jsonCar2Data.deviation2));
        }
        if (m_jsonCar2Data.hasLabel3) {
            ui->car2_label3->setText(QString::number(m_jsonCar2Data.label3));
        }
        if (m_jsonCar2Data.hasDeviation3) {
            ui->car2_dev3->setText(QString::number(m_jsonCar2Data.deviation3));
        }
        qDebug() << "Car2 data updated to UI (only existing fields)";
    }
    
    // 更新Drone数据到UI - 只更新JSON中存在的字段
    if (m_jsonDroneData.isValid) {
        if (m_jsonDroneData.hasLongitude) {
            ui->drone_long->setText(QString::number(m_jsonDroneData.longitude));
        }
        if (m_jsonDroneData.hasLatitude) {
            ui->drone_lat->setText(QString::number(m_jsonDroneData.latitude));
        }
        if (m_jsonDroneData.hasAltitude) {
            ui->drone_alt->setText(QString::number(m_jsonDroneData.altitude));
        }
        if (m_jsonDroneData.hasHeading) {
            ui->drone_heading->setText(QString::number(m_jsonDroneData.heading));
        }
        if (m_jsonDroneData.hasRoll) {
            ui->drone_roll->setText(QString::number(m_jsonDroneData.roll));
        }
        if (m_jsonDroneData.hasPitch) {
            ui->drone_pitch->setText(QString::number(m_jsonDroneData.pitch));
        }
        if (m_jsonDroneData.hasLabel1) {
            ui->drone_label1->setText(QString::number(m_jsonDroneData.label1));
        }
        // 只有当target1X和target1Y都存在时才更新target1输入框
        if (m_jsonDroneData.hasTarget1X && m_jsonDroneData.hasTarget1Y) {
            ui->drone_t1->setText(QString("%1,%2").arg(m_jsonDroneData.target1X).arg(m_jsonDroneData.target1Y));
        }
        if (m_jsonDroneData.hasLabel2) {
            ui->drone_label2->setText(QString::number(m_jsonDroneData.label2));
        }
        // 只有当target2X和target2Y都存在时才更新target2输入框
        if (m_jsonDroneData.hasTarget2X && m_jsonDroneData.hasTarget2Y) {
            ui->drone_t2->setText(QString("%1,%2").arg(m_jsonDroneData.target2X).arg(m_jsonDroneData.target2Y));
        }
        if (m_jsonDroneData.hasLabel3) {
            ui->drone_label3->setText(QString::number(m_jsonDroneData.label3));
        }
        // 只有当target3X和target3Y都存在时才更新target3输入框
        if (m_jsonDroneData.hasTarget3X && m_jsonDroneData.hasTarget3Y) {
            ui->drone_t3->setText(QString("%1,%2").arg(m_jsonDroneData.target3X).arg(m_jsonDroneData.target3Y));
        }
        qDebug() << "Drone data updated to UI (only existing fields)";
    }
}

// 获取当前设置的定时器间隔
int MainWindow::getCurrentInterval() const
{
    // 获取用户输入的频率值
    bool ok;
    double frequency = ui->lineEdit_frequency->text().toDouble(&ok);
    
    // 如果输入无效或频率小于等于0，使用默认频率1Hz（1000ms间隔）
    if (!ok || frequency <= 0) {
        return 1000;
    }
    
    // 计算定时器间隔（毫秒）= 1000 / 频率
    int interval = static_cast<int>(1000.0 / frequency);
    
    // 确保间隔至少为1毫秒
    if (interval < 1) interval = 1;
    
    return interval;
}

